#include "format_converter.h"
#include <cmath>

void FormatConverter::toGRAY(Image* image, int max_value)
{
	int size = image->width * image->height;
	unsigned char* new_data = new unsigned char[size];
	unsigned char* data = image->data;

	int bytesNum  = image->getBytesPerPixel();

	for(int i=0;i<size;i++)
	{
		double sum = 0;
		for(int j=0;j<bytesNum;j++)
		{
			sum += data[i*bytesNum+j];
		}
		double x = ((double)sum /bytesNum) ;
		double rate =((double)max_value / image->max_value);
		double y = x * rate + 0.5;
		new_data[i] = (int)floor(y);
	}

	delete[] image->data;
	image->data = new_data;

	if(max_value == 1) image->colorRange = MONO;
	else image->colorRange = GRAY;
	image->max_value = max_value;
}


void FormatConverter::toRGB(Image* image)
{

}

QImage FormatConverter::toQImage(Image* image)
{
	int bytesPerLine = image->width * 3;

	if(image->isGrayOrMono())
	{
		int chanelsCount = 3;
		int size = image->width * image->height * chanelsCount;
		unsigned char* new_data = new unsigned char[size];

		for(int i=0;i<size/chanelsCount;i++)
		{
			for(int j=0;j<chanelsCount;j++)
			{
				int param = 255/image->max_value;
				new_data[i*chanelsCount+j] = image->data[i] * param;
			}
		}

		QImage image(new_data, image->width, image->height, bytesPerLine ,QImage::Format_RGB888);
		return image.copy();
	}
	else if(image->colorRange == RGB)
	{
		QImage image(image->data, image->width, image->height, bytesPerLine, QImage::Format_RGB888);
		return image.copy();
	}
	
}


